package cn.derry.listener;

import cn.derry.domain.Account;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author MangoDai
 * @decription 登录的Session监听器
 * @date 2017/12/20
 **/
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener {
    private static AtomicInteger integer = new AtomicInteger(0);

    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {

    }

    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        Object value = httpSessionBindingEvent.getValue();
        if (value instanceof Account) {
            integer.incrementAndGet();
            Account account = (Account) value;
            System.out.println(account.getUsername() + " 上线了");
        }
    }

    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        Object value = httpSessionBindingEvent.getValue();
        if (value instanceof Account) {
            integer.decrementAndGet();
            Account account = (Account) value;
            System.out.println(account.getUsername() + " 下线了");
        }
    }

    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    public static AtomicInteger getOnlineCount() {
        return integer;
    }
}
